<script setup>
import { User, Lock, MoreFilled } from '@element-plus/icons-vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)

//定义数据模型
const registerData = ref({
    username: '',
    password: '',
    repassword: '',
    verifyCode: ''
})

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error('请确保两次输入的密码一样'))
    } else {
        callback()
    }
}

//定义表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 8, max: 16, message: '密码长度必须在8-16位之间', trigger: 'blur' },
        { 
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/,
            message: '密码必须包含大小写字母、数字和特殊字符',
            trigger: 'blur'
        }
    ],
    rePassword: [
        { validator: checkRePassword, trigger: 'blur' }
    ]
}

//调用后台接口完成注册
import { adminRegisterService, adminLoginService, getVerifyCodeService } from '@/api/admin.js'
const register = async () => {
    //registerData是一个响应式对象,如果要获取值,需要.value
    let result = await adminRegisterService(registerData.value);
    ElMessage.success(result.msg ? result.msg : '注册成功')
}

//绑定数据,复用注册表单的数据模型
//表单数据校验
//登录函数
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const tokenStore = useTokenStore();

// 添加登录失败相关的状态
const loginFailCount = ref(0)
const isLocked = ref(false)
const lockEndTime = ref(null)

// 检查账户是否被锁定
const checkLockStatus = () => {
    if (!isLocked.value || !lockEndTime.value) return false
    const now = new Date().getTime()
    if (now < lockEndTime.value) {
        const remainingMinutes = Math.ceil((lockEndTime.value - now) / (1000 * 60))
        ElMessage.error(`账户已被锁定，请在${remainingMinutes}分钟后重试`)
        return true
    }
    // 锁定时间已过
    isLocked.value = false
    lockEndTime.value = null
    loginFailCount.value = 0
    return false
}

// 添加会话超时处理
const TIMEOUT_DURATION = 30 * 60 * 1000; // 30分钟
let sessionTimer = null;

// 重置会话计时器
const resetSessionTimer = () => {
    if (sessionTimer) {
        clearTimeout(sessionTimer);
    }
    sessionTimer = setTimeout(() => {
        // 会话超时，执行登出操作
        tokenStore.removeToken();
        router.push('/login');
        ElMessage.warning('会话已超时，请重新登录');
    }, TIMEOUT_DURATION);
};

// 监听用户活动
const setupActivityListeners = () => {
    ['click', 'keypress', 'mousemove', 'scroll'].forEach(event => {
        document.addEventListener(event, resetSessionTimer);
    });
};

// 移除活动监听器
const removeActivityListeners = () => {
    ['click', 'keypress', 'mousemove', 'scroll'].forEach(event => {
        document.removeEventListener(event, resetSessionTimer);
    });
};

const login = async () => {
    // 检查是否被锁定
    if (checkLockStatus()) return

    try {
        // console.log("前端输入"+registerData.value.username+",密码输入"+registerData.value.password+", 验证码输入"+registerData.value.verifyCode)
        //调用接口,完成登录
        let result = await adminLoginService({
            ...registerData.value,
            verifyCode: registerData.value.verifyCode
        });
        
        // 登录成功，重置失败次数
        loginFailCount.value = 0
        ElMessage.success(result.msg ? result.msg : '登录成功')
        //把得到的token存储到pinia中
        tokenStore.setToken(result.data)
        // 登录成功后启动会话监控
        setupActivityListeners();
        resetSessionTimer();
        
        router.push('/layout')
    } catch (error) {
        // 登录失败，增加失败次数
        loginFailCount.value++
        
        // 检查是否需要锁定账户
        if (loginFailCount.value >= 5) {
            isLocked.value = true
            lockEndTime.value = new Date().getTime() + 30 * 60 * 1000 // 30分钟后
            ElMessage.error('登录失败次数过多，账户已被锁定30分钟')
            return
        }
        
        ElMessage.error(`登录失败，还剩${5 - loginFailCount.value}次机会`)
    }
}

// 定义验证码相关数据
const captchaImage = ref(null);

// 获取验证码图片的函数
const updateCaptcha = async () => {
    try {
        // 如果存在旧的 URL，先释放它
        if (captchaImage.value) {
            URL.revokeObjectURL(captchaImage.value);
        }

        const response = await getVerifyCodeService();
        const blob = new Blob([response.data], { type: 'image/png' });
        captchaImage.value = URL.createObjectURL(blob); // 直接更新响应式引用
    } catch (error) {
        console.error('Failed to fetch captcha image:', error);
        ElMessage.error('获取验证码失败');
    }
};

onMounted(() => {
    // 页面加载时获取验证码图片
    updateCaptcha();
});
//定义函数,清空数据模型的数据
const clearRegisterData = () => {
    registerData.value = {
        username: '',
        password: '',
        rePassword: ''
    }
}

// 组件卸载时清理
onUnmounted(() => {
    if (sessionTimer) {
        clearTimeout(sessionTimer);
    }
    removeActivityListeners();
});

</script>

<template>
    <div>
        <!-- 注册表单
        <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"
            class="form">
            <el-form-item> -->
        <!-- <img src="@/assets/loginPage.png" alt="背景图" class="background-image"> -->
        <!-- <h1>注册</h1>
            </el-form-item>
            <el-form-item prop="username">
                <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
            </el-form-item>
            <el-form-item prop="rePassword">
                <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                    v-model="registerData.repassword"></el-input>
            </el-form-item> -->
        <!-- 注册按钮 -->
        <!-- <el-form-item>
                <el-button class="button" type="primary" auto-insert-space @click="register">
                    注册
                </el-button>
            </el-form-item>
            <el-form-item class="flex">
                <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">
                    ← 返回
                </el-link>
            </el-form-item>
        </el-form> -->
    </div>
    <!-- 登录表单 -->
    <div class="form-container" style="background-color: rgb(242, 246, 250);">
    <!-- 图片+文字 -->
    <div class="header-section">
        <img src="@/assets/login.png" alt="背景图" class="background-image">
    </div>

    <!-- 登录表单 -->
    <el-form ref="form" size="large" autocomplete="off" :model="registerData" :rules="rules" class="form">
        <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                v-model="registerData.password"></el-input>
        </el-form-item>
        <!-- 验证码部分 -->
        <el-form-item prop="verifyCode" class="captcha-container">
            <el-row :gutter="10">
                <el-col :span="16">
                    <el-input placeholder="请输入验证码" :prefix-icon="MoreFilled"
                        v-model="registerData.verifyCode"></el-input>
                </el-col>
                <el-col :span="8">
                    <img :src="captchaImage" id="captchaImage" alt="验证码" @click="updateCaptcha"
                        style="cursor:pointer; width: 100%;" />
                </el-col>
            </el-row>
        </el-form-item>

        <el-form-item class="flex">
            <div class="flex">
                <el-checkbox>记住我</el-checkbox>
            </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
            <el-button class="button" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
    </el-form>
</div>
</template>

<style lang="scss" scoped>

.form-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f7f7f7; /* 轻微的背景颜色 */
    padding: 20px; /* 根据需要调整 */
}

.header-section {
    position: relative;
    width: 100%; /* 确保与表单宽度一致 */
    max-width: 400px; /* 与表单的最大宽度相同 */
    margin-bottom: -40px; /* 调整负边距使图片覆盖表单上部 */
    text-align: center;
    z-index: 1; /* 确保图片位于表单之上 */
}

.header-section .background-image {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 0 auto;
    border-radius: 8px;
}

.form {
    width: 100%;
    max-width: 400px;
    min-width: 300px;
    background-color: #ffffff;
    padding: 40px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    box-sizing: border-box;
    position: relative;
    z-index: 0; /* 确保表单位于图片之下 */
}


h1 {
    text-align: center;
    margin-bottom: 30px;
    color: #333; // 深色标题
}

.el-form-item {
    margin-bottom: 24px; // 增加表单项之间的间距
}

.el-input {
    input {
        border-radius: 4px; // 输入框圆角
        height: 40px; // 输入框高度
        font-size: 16px; // 输入框字体大小
    }
}

.el-button {
    background-color: #7c96df;
    width: 100%; // 按钮宽度充满父元素
    border-radius: 5px; // 按钮圆角
    height: 50px; // 按钮高度
    font-size: 18px; // 按钮字体大小
    color: #fff; // 鼠标悬停时字体颜色变为白色
    transition: all 0.3s ease; // 添加过渡效果
}

.el-button:hover {
    background-color: #9ca5c7;
}
.flex {
    display: flex;
    justify-content: space-between; // 分散对齐
    justify-content: right;
    align-items: right; // 垂直居中
}

.el-link {
    font-size: 14px; // 链接字体大小
}

// 添加过渡效果
.el-form-item,
.el-button,
.el-input {
    transition: all 0.3s ease; // 平滑过渡效果
}

.captcha-container {
    display: flex;
    align-items: center;


    .el-input {
        flex-grow: 1;
        margin-right: 10px; // 调整输入框和验证码图片之间的间距
        
    }

    img {border-radius: 4px;
        cursor: pointer;
        width: 100%;
        height: auto;
       margin-top: 5px;
    }
}</style>
